<template>
  <div class="supplier-management-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>供应商管理</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleCreate"
              >新建供应商</el-button
            >
            <el-upload
              class="upload-btn"
              :action="uploadUrl"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
            >
              <el-button type="primary">导入供应商</el-button>
            </el-upload>
            <el-button type="primary" @click="handleExport"
              >导出供应商</el-button
            >
          </div>
        </div>
      </template>

      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="供应商编码">
          <el-input v-model="queryForm.code" placeholder="请输入供应商编码" />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="queryForm.name" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="供应商类型">
          <el-select
            v-model="queryForm.type"
            placeholder="请选择供应商类型"
            clearable
          >
            <el-option label="生产厂商" value="manufacturer" />
            <el-option label="代理商" value="agent" />
            <el-option label="贸易商" value="trader" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="等级">
          <el-select
            v-model="queryForm.level"
            placeholder="请选择等级"
            clearable
          >
            <el-option label="A级" value="A" />
            <el-option label="B级" value="B" />
            <el-option label="C级" value="C" />
            <el-option label="D级" value="D" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="合作中" value="active" />
            <el-option label="已终止" value="terminated" />
            <el-option label="已冻结" value="frozen" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="expand">
          <template #default="props">
            <el-tabs v-model="activeTab">
              <el-tab-pane label="联系人信息" name="contacts">
                <div class="contact-header">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleAddContact(props.row)"
                  >
                    新增联系人
                  </el-button>
                </div>
                <el-table :data="props.row.contacts" border>
                  <el-table-column prop="name" label="姓名" width="120" />
                  <el-table-column prop="position" label="职位" width="120" />
                  <el-table-column prop="phone" label="电话" width="150" />
                  <el-table-column prop="email" label="邮箱" min-width="180" />
                  <el-table-column
                    prop="isMain"
                    label="是否主要联系人"
                    width="120"
                  >
                    <template #default="scope">
                      <el-tag :type="scope.row.isMain ? 'success' : 'info'">
                        {{ scope.row.isMain ? "是" : "否" }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="150">
                    <template #default="scope">
                      <el-button
                        link
                        type="primary"
                        @click="handleEditContact(props.row, scope.row)"
                        >编辑</el-button
                      >
                      <el-button
                        link
                        type="danger"
                        @click="handleDeleteContact(props.row, scope.row)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="资质信息" name="qualifications">
                <div class="qualification-header">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleAddQualification(props.row)"
                  >
                    新增资质
                  </el-button>
                </div>
                <el-table :data="props.row.qualifications" border>
                  <el-table-column
                    prop="name"
                    label="资质名称"
                    min-width="150"
                  />
                  <el-table-column prop="code" label="证书编号" width="180" />
                  <el-table-column
                    prop="issueDate"
                    label="发证日期"
                    width="120"
                  />
                  <el-table-column
                    prop="expiryDate"
                    label="有效期至"
                    width="120"
                  />
                  <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                      <el-tag :type="getQualificationStatusType(scope.row)">
                        {{ getQualificationStatusText(scope.row) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="200">
                    <template #default="scope">
                      <el-button
                        link
                        type="primary"
                        @click="handleEditQualification(props.row, scope.row)"
                        >编辑</el-button
                      >
                      <el-button
                        link
                        type="primary"
                        @click="handleViewQualification(scope.row)"
                        >查看</el-button
                      >
                      <el-button
                        link
                        type="danger"
                        @click="handleDeleteQualification(props.row, scope.row)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="供应物料" name="materials">
                <div class="material-header">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleAddMaterial(props.row)"
                  >
                    新增物料
                  </el-button>
                </div>
                <el-table :data="props.row.materials" border>
                  <el-table-column prop="code" label="物料编码" width="150" />
                  <el-table-column
                    prop="name"
                    label="物料名称"
                    min-width="150"
                  />
                  <el-table-column
                    prop="specification"
                    label="规格型号"
                    width="120"
                  />
                  <el-table-column prop="unit" label="单位" width="80" />
                  <el-table-column prop="price" label="采购价格" width="120" />
                  <el-table-column
                    prop="minQuantity"
                    label="最小订购量"
                    width="120"
                  />
                  <el-table-column
                    prop="leadTime"
                    label="供货周期(天)"
                    width="120"
                  />
                  <el-table-column label="操作" width="150">
                    <template #default="scope">
                      <el-button
                        link
                        type="primary"
                        @click="handleEditMaterial(props.row, scope.row)"
                        >编辑</el-button
                      >
                      <el-button
                        link
                        type="danger"
                        @click="handleDeleteMaterial(props.row, scope.row)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="评价记录" name="evaluations">
                <div class="evaluation-header">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleAddEvaluation(props.row)"
                  >
                    新增评价
                  </el-button>
                </div>
                <el-table :data="props.row.evaluations" border>
                  <el-table-column prop="date" label="评价日期" width="120" />
                  <el-table-column prop="period" label="评价周期" width="120" />
                  <el-table-column
                    prop="qualityScore"
                    label="质量得分"
                    width="100"
                  />
                  <el-table-column
                    prop="deliveryScore"
                    label="交付得分"
                    width="100"
                  />
                  <el-table-column
                    prop="serviceScore"
                    label="服务得分"
                    width="100"
                  />
                  <el-table-column prop="totalScore" label="总分" width="100" />
                  <el-table-column prop="level" label="评价等级" width="100">
                    <template #default="scope">
                      <el-tag :type="getEvaluationLevelType(scope.row.level)">
                        {{ scope.row.level }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="evaluator"
                    label="评价人"
                    width="120"
                  />
                  <el-table-column
                    prop="remark"
                    label="评价说明"
                    min-width="200"
                    show-overflow-tooltip
                  />
                  <el-table-column label="操作" width="150">
                    <template #default="scope">
                      <el-button
                        link
                        type="primary"
                        @click="handleViewEvaluation(scope.row)"
                        >查看</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="供应商编码" width="120" />
        <el-table-column prop="name" label="供应商名称" min-width="200" />
        <el-table-column prop="type" label="供应商类型" width="120">
          <template #default="scope">
            <el-tag>{{ getSupplierTypeText(scope.row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="等级" width="80">
          <template #default="scope">
            <el-tag :type="getSupplierLevelType(scope.row.level)">
              {{ scope.row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getSupplierStatusType(scope.row.status)">
              {{ getSupplierStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="地址"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button link type="primary" @click="handleViewHistory(scope.row)"
              >历史</el-button
            >
            <el-dropdown>
              <el-button link type="primary">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleFreeze(scope.row)">
                    {{ scope.row.status === "frozen" ? "解冻" : "冻结" }}
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleTerminate(scope.row)">
                    {{
                      scope.row.status === "terminated"
                        ? "恢复合作"
                        : "终止合作"
                    }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 供应商表单对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'create' ? '新建供应商' : '编辑供应商'"
        width="60%"
      >
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-tabs v-model="formActiveTab">
            <el-tab-pane label="基本信息" name="basic">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="供应商编码" prop="code">
                    <el-input
                      v-model="form.code"
                      :disabled="dialogType === 'edit'"
                      placeholder="请输入供应商编码"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="供应商名称" prop="name">
                    <el-input
                      v-model="form.name"
                      placeholder="请输入供应商名称"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="供应商类型" prop="type">
                    <el-select
                      v-model="form.type"
                      placeholder="请选择供应商类型"
                    >
                      <el-option label="生产厂商" value="manufacturer" />
                      <el-option label="代理商" value="agent" />
                      <el-option label="贸易商" value="trader" />
                      <el-option label="其他" value="other" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="等级" prop="level">
                    <el-select v-model="form.level" placeholder="请选择等级">
                      <el-option label="A级" value="A" />
                      <el-option label="B级" value="B" />
                      <el-option label="C级" value="C" />
                      <el-option label="D级" value="D" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入地址" />
              </el-form-item>

              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注"
                />
              </el-form-item>
            </el-tab-pane>

            <el-tab-pane label="企业信息" name="company">
              <el-form-item label="统一社会信用代码" prop="creditCode">
                <el-input
                  v-model="form.creditCode"
                  placeholder="请输入统一社会信用代码"
                />
              </el-form-item>
              <el-form-item label="法定代表人" prop="legalRepresentative">
                <el-input
                  v-model="form.legalRepresentative"
                  placeholder="请输入法定代表人"
                />
              </el-form-item>
              <el-form-item label="注册资本" prop="registeredCapital">
                <el-input
                  v-model="form.registeredCapital"
                  placeholder="请输入注册资本"
                />
              </el-form-item>
              <el-form-item label="成立日期" prop="establishDate">
                <el-date-picker
                  v-model="form.establishDate"
                  type="date"
                  placeholder="请选择成立日期"
                />
              </el-form-item>
              <el-form-item label="经营范围" prop="businessScope">
                <el-input
                  v-model="form.businessScope"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入经营范围"
                />
              </el-form-item>
            </el-tab-pane>

            <el-tab-pane label="结算信息" name="settlement">
              <el-form-item label="开户银行" prop="bankName">
                <el-input
                  v-model="form.bankName"
                  placeholder="请输入开户银行"
                />
              </el-form-item>
              <el-form-item label="银行账号" prop="bankAccount">
                <el-input
                  v-model="form.bankAccount"
                  placeholder="请输入银行账号"
                />
              </el-form-item>
              <el-form-item label="开户名" prop="accountName">
                <el-input
                  v-model="form.accountName"
                  placeholder="请输入开户名"
                />
              </el-form-item>
              <el-form-item label="发票类型" prop="invoiceType">
                <el-select
                  v-model="form.invoiceType"
                  placeholder="请选择发票类型"
                >
                  <el-option label="增值税专用发票" value="special" />
                  <el-option label="增值税普通发票" value="normal" />
                </el-select>
              </el-form-item>
              <el-form-item label="税率" prop="taxRate">
                <el-input-number
                  v-model="form.taxRate"
                  :min="0"
                  :max="100"
                  :precision="2"
                  :step="0.01"
                />
              </el-form-item>
              <el-form-item label="付款方式" prop="paymentMethod">
                <el-select
                  v-model="form.paymentMethod"
                  placeholder="请选择付款方式"
                >
                  <el-option label="电汇" value="wire" />
                  <el-option label="支票" value="check" />
                  <el-option label="承兑" value="acceptance" />
                </el-select>
              </el-form-item>
              <el-form-item label="付款条件" prop="paymentTerm">
                <el-input
                  v-model="form.paymentTerm"
                  placeholder="请输入付款条件"
                />
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 其他相关对话框（联系人、资质、物料、评价等） -->
      <!-- ... 省略其他对话框的具体实现 ... -->
    </el-card>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowDown } from "@element-plus/icons-vue";

// ... 省略状态定义和方法实现 ...

// 获取供应商类型文本
const getSupplierTypeText = (type) => {
  const map = {
    manufacturer: "生产厂商",
    agent: "代理商",
    trader: "贸易商",
    other: "其他",
  };
  return map[type] || type;
};

// 获取供应商等级样式
const getSupplierLevelType = (level) => {
  const map = {
    A: "success",
    B: "warning",
    C: "info",
    D: "danger",
  };
  return map[level] || "";
};

// 获取供应商状态样式
const getSupplierStatusType = (status) => {
  const map = {
    active: "success",
    terminated: "danger",
    frozen: "warning",
  };
  return map[status] || "";
};

// 获取供应商状态文本
const getSupplierStatusText = (status) => {
  const map = {
    active: "合作中",
    terminated: "已终止",
    frozen: "已冻结",
  };
  return map[status] || status;
};

// 获取资质状态样式
const getQualificationStatusType = (qualification) => {
  const now = new Date();
  const expiryDate = new Date(qualification.expiryDate);
  if (expiryDate < now) return "danger";
  if (expiryDate - now < 30 * 24 * 60 * 60 * 1000) return "warning";
  return "success";
};

// 获取资质状态文本
const getQualificationStatusText = (qualification) => {
  const now = new Date();
  const expiryDate = new Date(qualification.expiryDate);
  if (expiryDate < now) return "已过期";
  if (expiryDate - now < 30 * 24 * 60 * 60 * 1000) return "即将过期";
  return "有效";
};

// 获取评价等级样式
const getEvaluationLevelType = (level) => {
  const map = {
    A: "success",
    B: "warning",
    C: "info",
    D: "danger",
  };
  return map[level] || "";
};

// 导入相关方法
const beforeUpload = (file) => {
  const isExcel =
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
    file.type === "application/vnd.ms-excel";
  if (!isExcel) {
    ElMessage.error("只能上传 Excel 文件!");
    return false;
  }
  return true;
};

const handleUploadSuccess = (response) => {
  if (response.success) {
    ElMessage.success("导入成功");
    handleSearch();
  } else {
    ElMessage.error(response.message || "导入失败");
  }
};

// 导出方法
const handleExport = () => {
  // 实现导出逻辑
  ElMessage.success("导出成功");
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};
</script>

<style scoped>
.supplier-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.contact-header,
.qualification-header,
.material-header,
.evaluation-header {
  margin-bottom: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.ml-5 {
  margin-left: 5px;
}

.dialog-footer {
  text-align: right;
}
</style>
